﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;

namespace SgMotionSample
{
    public class InputComponent : GameComponent
    {
        protected KeyboardState LastKey;
        protected GamePadState[] LastPad = new GamePadState[4];
        protected MouseState LastMouse;
        protected KeyboardState CurrentKey;
        protected readonly GamePadState[] CurrentPad = new GamePadState[4];
        protected MouseState CurrentMouse;

        public PlayerIndex? CurrentGamePad;

        public InputComponent(Game game)
            : base(game)
        {
        }

        public override void Update(GameTime gameTime)
        {
            //Move to next frame, remembering values from last frame
            LastKey = CurrentKey;
            LastMouse = CurrentMouse;
            CurrentKey = Keyboard.GetState();
            CurrentMouse = Mouse.GetState();
            for (int i = 0; i < (int)PlayerIndex.Four; i++)
            {
                LastPad[i] = CurrentPad[i];
                CurrentPad[i] = GamePad.GetState((PlayerIndex) i);
            }

            
            base.Update(gameTime);
        }

        public bool KeyPressed(Keys key)
        {
            return (LastKey.IsKeyUp(key) && CurrentKey.IsKeyDown(key));
        }

        public bool PadPressed(Buttons button)
        {
            if (CurrentGamePad != null)
            {
                return PadPressed(button, CurrentGamePad.Value);
            }

            for (var i = 0; i < (int)PlayerIndex.Four; i++)
            {
                if (PadPressed(button, (PlayerIndex)i)) return true;  //Early out as soon as we find one controller
            }
            return false;
        }

        private bool PadPressed(Buttons button, PlayerIndex gamePad)
        {
            return (LastPad[(int) gamePad].IsButtonUp(button) && CurrentPad[(int) gamePad].IsButtonDown(button));
        }

        public int ScrollWheel
        {
            get { return CurrentMouse.ScrollWheelValue; }
        }
    }
}
